using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization;
using Orchard.UI.Notify;
using Mod.DisplayTypes.Models;
using Mod.DisplayTypes.Settings;
using System;
using Orchard.Tokens;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;

namespace Mod.DisplayTypes.Drivers
{
    [UsedImplicitly]
	
    public class DisplayTypePartDriver : ContentPartDriver<DisplayTypePart>
    {
        private readonly INotifier _notifier;
        private readonly ITokenizer tokenizer;
        private const string TemplateName = "Parts/DisplayTypePart";

        public Localizer T { get; set; }

        public DisplayTypePartDriver(INotifier notifier, ITokenizer tokenizer)
        {
            _notifier = notifier;
            this.tokenizer = tokenizer;
            T = NullLocalizer.Instance;
        }

        protected override DriverResult Display(DisplayTypePart part, string displayType, dynamic shapeHelper)
        {
            return ContentShape("Parts_DisplayTypePart",
                () => shapeHelper.Parts_DisplayTypePart(ContentItem: part.ContentItem));
        }

        protected override DriverResult Editor(DisplayTypePart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_DisplayTypePart",
                    () => shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: part, Prefix: Prefix));
        }

        protected override DriverResult Editor(DisplayTypePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var typeSettings = part.Settings.GetModel<DisplayTypePartTypePartSettings>();
            var id = part.Id;

            var routes = typeSettings.RouteList;
            try
            {
                foreach (var r in routes)
                {
                    var path = r.Slugs;
                    var tPath = tokenizer.Replace(path, new Dictionary<string, object> { { "Content", part.ContentItem } }, new ReplaceOptions { Encoding = ReplaceOptions.NoEncode });
                    tPath = tPath.TrimStart('/', '\\');

                    r.Slugs = tPath;
                }

                // serialize
                var sz = new JavaScriptSerializer().Serialize(routes.ToArray());
                part.Pathz = sz;

                if (updater.TryUpdateModel(part, Prefix, null, null))
                {
                }
                else
                {
                    _notifier.Error(T("Error updating display type"));
                }
            }
            catch(Exception ex) {
                _notifier.Error(T("Error updating display type"));
            }

            return Editor(part, shapeHelper);
        }

    }
}